package main

import (
	"fmt"
	"time"

	"github.com/jmoiron/sqlx"
)

type server struct {
	db *sqlx.DB
}

func NewServer(cfg ServerConfig) (*server, error) {
	db, err := sqlx.Connect(cfg.Driver, cfg.DSN)
	if err != nil {
		return nil, err
	}
	s := server{
		db: db,
	}
	return &s, nil
}

func (s *server) GetLatestDataByMMSI(mmsi int, startTime time.Time) ([]ShipData, error) {
	ship := Ship{}
	err := s.db.Get(&ship, "select id, name, m_m_s_i from ship where m_m_s_i = ?", mmsi)
	if err != nil {
		return nil, err
	}
	shipGeos := []ShipGeo{}
	if startTime.IsZero() {
		startTime = time.Now()
	}
	query := fmt.Sprintf("select longitude, latitude, time, speed from shipgeo_%d where time > ?", ship.ID)
	err = s.db.Select(&shipGeos, query, startTime)
	if err != nil {
		return []ShipData{}, err
	}
	sd := make([]ShipData, len(shipGeos))
	for idx, sg := range shipGeos {
		sd[idx] = ShipData{
			ship,
			sg,
		}
	}
	return sd, nil
}
